#!/usr/bin/env python3
"""
微信小程序抢号程序 - MVP版本
针对电脑版微信小程序的操作
"""

import time
import yaml
import random
import pyautogui
import cv2
import numpy as np
from loguru import logger


class WeChatMiniProgramGrabber:
    """微信小程序抢号器 - MVP版本"""
    
    def __init__(self, config_file="config.yaml"):
        """初始化"""
        self.config = self.load_config(config_file)
        self.setup_logging()
        self.setup_pyautogui()
        
    def load_config(self, config_file):
        """加载配置"""
        try:
            with open(config_file, 'r', encoding='utf-8') as f:
                return yaml.safe_load(f)
        except Exception as e:
            logger.error(f"加载配置文件失败: {e}")
            return {}
    
    def setup_logging(self):
        """设置日志"""
        log_config = self.config.get('logging', {})
        logger.add(
            log_config.get('file', 'grab.log'),
            level=log_config.get('level', 'INFO'),
            format="{time} | {level} | {message}"
        )
    
    def setup_pyautogui(self):
        """设置PyAutoGUI"""
        # 设置安全边界，防止鼠标移动到角落
        pyautogui.FAILSAFE = True
        # 设置操作间隔
        pyautogui.PAUSE = 0.1
        
    def find_wechat_window(self):
        """查找微信窗口"""
        try:
            # 使用图像识别查找微信窗口
            wechat_icon = self.config.get('target', {}).get('wechat_icon', 'images/wechat_icon.png')
            
            # 截取屏幕
            screenshot = pyautogui.screenshot()
            screenshot_np = np.array(screenshot)
            screenshot_cv = cv2.cvtColor(screenshot_np, cv2.COLOR_RGB2BGR)
            
            # 读取微信图标模板
            template = cv2.imread(wechat_icon)
            if template is None:
                logger.warning("未找到微信图标模板，请确保images/wechat_icon.png存在")
                return None
            
            # 模板匹配
            result = cv2.matchTemplate(screenshot_cv, template, cv2.TM_CCOEFF_NORMED)
            min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(result)
            
            if max_val >= 0.8:  # 匹配度阈值
                logger.info(f"找到微信窗口，位置: {max_loc}")
                return max_loc
            else:
                logger.warning("未找到微信窗口")
                return None
                
        except Exception as e:
            logger.error(f"查找微信窗口失败: {e}")
            return None
    
    def open_mini_program(self):
        """打开小程序"""
        try:
            # 获取小程序配置
            mini_program = self.config.get('target', {}).get('mini_program', {})
            search_text = mini_program.get('search_text', '')
            
            if not search_text:
                logger.error("未配置小程序搜索文本")
                return False
            
            # 点击微信搜索框
            search_box_pos = self.config.get('target', {}).get('search_box_pos', (200, 100))
            pyautogui.click(search_box_pos[0], search_box_pos[1])
            time.sleep(0.5)
            
            # 输入小程序名称
            pyautogui.typewrite(search_text)
            time.sleep(1)
            
            # 按回车搜索
            pyautogui.press('enter')
            time.sleep(2)
            
            logger.info(f"已搜索小程序: {search_text}")
            return True
            
        except Exception as e:
            logger.error(f"打开小程序失败: {e}")
            return False
    
    def locate_grab_button(self):
        """定位抢号按钮"""
        try:
            # 获取按钮配置
            button_config = self.config.get('target', {}).get('grab_button', {})
            
            # 方法1: 图像识别
            if 'image' in button_config:
                button_image = button_config['image']
                location = pyautogui.locateOnScreen(button_image, confidence=0.8)
                if location:
                    logger.info(f"通过图像识别找到抢号按钮: {location}")
                    return pyautogui.center(location)
            
            # 方法2: 固定坐标
            if 'position' in button_config:
                pos = button_config['position']
                logger.info(f"使用固定坐标: {pos}")
                return pos
            
            # 方法3: 相对位置
            if 'relative' in button_config:
                rel = button_config['relative']
                # 基于微信窗口的相对位置
                wechat_pos = self.find_wechat_window()
                if wechat_pos:
                    abs_pos = (wechat_pos[0] + rel[0], wechat_pos[1] + rel[1])
                    logger.info(f"使用相对坐标: {abs_pos}")
                    return abs_pos
            
            logger.warning("未找到抢号按钮")
            return None
            
        except Exception as e:
            logger.error(f"定位抢号按钮失败: {e}")
            return None
    
    def click_grab_button(self, button_pos):
        """点击抢号按钮"""
        try:
            if button_pos:
                # 移动到按钮位置
                pyautogui.moveTo(button_pos[0], button_pos[1], duration=0.2)
                time.sleep(0.1)
                
                # 点击按钮
                pyautogui.click()
                logger.success("抢号按钮点击成功！")
                return True
            else:
                logger.error("按钮位置为空")
                return False
                
        except Exception as e:
            logger.error(f"点击抢号按钮失败: {e}")
            return False
    
    def check_success(self):
        """检查抢号是否成功"""
        try:
            # 获取成功标识配置
            success_config = self.config.get('target', {}).get('success_indicator', {})
            
            # 方法1: 图像识别成功标识
            if 'success_image' in success_config:
                success_image = success_config['success_image']
                location = pyautogui.locateOnScreen(success_image, confidence=0.8)
                if location:
                    logger.success("检测到成功标识图像")
                    return True
            
            # 方法2: 检查特定颜色区域
            if 'color_check' in success_config:
                color_config = success_config['color_check']
                x, y = color_config['position']
                color = pyautogui.pixel(x, y)
                target_color = color_config['color']
                
                # 简单的颜色匹配
                if abs(color[0] - target_color[0]) < 20 and \
                   abs(color[1] - target_color[1]) < 20 and \
                   abs(color[2] - target_color[2]) < 20:
                    logger.success("检测到成功标识颜色")
                    return True
            
            # 方法3: 检查文本（需要OCR，这里简化处理）
            if 'text_check' in success_config:
                # 这里可以集成OCR功能
                logger.info("文本检查功能需要OCR支持")
            
            # 默认返回False，避免误判
            return False
            
        except Exception as e:
            logger.error(f"检查成功状态失败: {e}")
            return False
    
    def grab_number(self):
        """抢号主逻辑"""
        try:
            interval = self.config.get('automation', {}).get('interval', 1.0)
            max_retries = self.config.get('automation', {}).get('max_retries', 3)
            
            logger.info("开始抢号...")
            logger.info(f"抢号间隔: {interval}秒")
            
            attempt_count = 0
            
            while True:
                attempt_count += 1
                logger.info(f"第 {attempt_count} 次尝试抢号")
                
                # 定位抢号按钮
                button_pos = self.locate_grab_button()
                
                if button_pos:
                    # 点击抢号按钮
                    if self.click_grab_button(button_pos):
                        # 等待结果
                        time.sleep(2)
                        
                        # 检查是否成功
                        if self.check_success():
                            logger.success("🎉 抢号成功！")
                            return True
                        else:
                            logger.warning("抢号失败，继续尝试...")
                else:
                    logger.warning("未找到抢号按钮，可能还未开放抢号")
                
                # 等待下次尝试
                time.sleep(interval + random.uniform(0, 0.5))
                
        except KeyboardInterrupt:
            logger.info("用户中断抢号")
            return False
        except Exception as e:
            logger.error(f"抢号过程异常: {e}")
            return False
    
    def run(self):
        """运行抢号程序"""
        try:
            logger.info("=== 微信小程序抢号程序 ===")
            logger.info("请确保：")
            logger.info("1. 电脑版微信已打开并登录")
            logger.info("2. 目标小程序已打开")
            logger.info("3. 抢号按钮可见")
            logger.info()
            
            # 等待用户准备
            input("准备就绪后按回车开始抢号...")
            
            # 开始抢号
            success = self.grab_number()
            
            if success:
                logger.success("抢号程序执行完成")
            else:
                logger.warning("抢号程序执行失败")
            
            return success
            
        except Exception as e:
            logger.error(f"程序运行异常: {e}")
            return False


def main():
    """主函数"""
    print("=== 微信小程序抢号程序 MVP版本 ===")
    print("注意：此程序针对电脑版微信小程序")
    print("需要手动打开微信和小程序")
    print()
    
    # 创建抢号器
    grabber = WeChatMiniProgramGrabber()
    
    # 运行抢号
    success = grabber.run()
    
    if success:
        print("✅ 抢号程序执行成功")
    else:
        print("❌ 抢号程序执行失败")
    
    input("按回车键退出...")


if __name__ == "__main__":
    main() 